﻿
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;

namespace WSU.ChekaParallel.TestThread.Coordinate
{
    static class TestCountdownEvent
    {
        private static void CheckCountdownEvent(CountdownEvent countEvt)
        {
            Console.WriteLine("when started, total count is {0}",countEvt.InitialCount);
            Debug.Assert(!countEvt.IsSet);

            Task[] tasks = new Task[countEvt.InitialCount];
            for (int index = 0; index < countEvt.InitialCount; ++index)
            {
                int temp = index;
                tasks[index] = Task.Factory.StartNew(() =>
                {
                    Thread.Sleep(temp * 1000);
                    Console.WriteLine("Task-{0} completed,event's current count={1}", temp, countEvt.CurrentCount);
                    countEvt.Signal();
                });
            }

            countEvt.Wait();
            Debug.Assert(countEvt.IsSet);
            Console.WriteLine("----------------- CountdownEvent decreased to zero.");

            // actually it is not necessary to wait for the tasks, but it is believed to be a good practice
            Task.WaitAll(tasks);
        }

        public static void TestMain()
        {
            using (CountdownEvent countEvent = new CountdownEvent(3))
            {
                CheckCountdownEvent(countEvent);

                // countEvent.Reset();// reset without any argument just reset to previous total count
                countEvent.Reset(4);// give a new count
                CheckCountdownEvent(countEvent);
            }
        }
    }
}